package net.imwork.amorgemini.service.impl;

import net.imwork.amorgemini.core.dict.ExceptionDict;
import net.imwork.amorgemini.core.exception.BaseException;
import net.imwork.amorgemini.core.utils.MD5Util;
import net.imwork.amorgemini.entity.SysUser;
import net.imwork.amorgemini.repository.mysql.UserRepository;
import net.imwork.amorgemini.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by lvbr on 2017-07-29 17:33.
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserRepository userRepository;

    @Override
    public List<SysUser> findAll() {
        return userRepository.findAll();
    }

    @Override
    public SysUser save(SysUser entity) {
        return userRepository.save(entity);
    }

    @Override
    public void delete(Integer id) {
        userRepository.delete(id);
    }

    @Override
    public SysUser update(SysUser entity) {
        return userRepository.save(entity);
    }

    @Override
    public SysUser getOne(Integer id) {
        return userRepository.getOne(id);
    }

    @Override
    public SysUser register(SysUser user) {
        if (null != userRepository.getByUname(user.getUname())) {
            throw new BaseException(ExceptionDict.EXISTS_ERROR);
        }
        String salt = MD5Util.getSalt();
        user.setSalt(salt);
        user.setPwd(MD5Util.encode(user.getPwd(), salt));
        return userRepository.save(user);
    }

    @Override
    public SysUser login(SysUser user) {
        SysUser dbu = userRepository.getByUname(user.getUname());
        if (null == dbu || !dbu.getPwd().equals(MD5Util.encode(user.getPwd(), dbu.getSalt()))) {
            throw new BaseException(ExceptionDict.LOGIN_ERROR);
        }
        return dbu;
    }
}
